package utils

import (
	"strings"
	"google.golang.org/grpc/naming"
)

type resolver struct {
	ch			  chan *naming.Update
}

func NewResolver(ch	chan *naming.Update) *resolver{
	return &resolver{ch}
}

func (re *resolver) Resolve(target string) (naming.Watcher, error) {
	// Return watcher
	return &watcher{re: re, target: target}, nil
}

type watcher struct {
	re            *resolver
	target		  string
	isInitialized bool
}

func (w *watcher) Close() {
}

// Next to return the updates
func (w *watcher) Next() ([]*naming.Update, error) {

	// check if is initialized
	if !w.isInitialized {
		addrs := strings.Split(w.target,",")
		w.isInitialized = true
		//if not empty, return the updates
		if l := len(addrs); l != 0 {
			updates := make([]*naming.Update, l)
			for i := range addrs {
				updates[i] = &naming.Update{Op: naming.Add, Addr: addrs[i]}
			}
			return updates, nil
		}

	}

	for update := range w.re.ch {
		return []*naming.Update{update}, nil
	}

	return nil, nil
}

